﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Reflection;
using System.Text;

public partial class MB_Registration : System.Web.UI.Page
{
    protected void Page_PreInit(object sender, EventArgs e)
    {
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            loadCombolists();
        if (Request.UrlReferrer != null && Request.UrlReferrer.ToString() != "")
            if (Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.LastIndexOf('/')) != Request.UrlReferrer.ToString().Substring(0, Request.UrlReferrer.ToString().LastIndexOf('/')))
                btn_back.Visible = true;
    }
    private string wrapItAsMessage(string msg, bool isError)
    {
        return "<div class=\"" + (isError == true ? "mbErrorMessage" : "mbMessage") + "\">" + msg + "</div>";
    }
    private void loadCombolists()
    {
        HDDatabase HDD = null;
        try
        {
            if (Session["servercon"] != null && Session["servercon"].ToString() != "")
                HDD = new HDDatabase(Session["servercon"].ToString());
            else
                HDD = new HDDatabase();
            
            DataTable dt_pwdHint = HDD.GetDataTable("select mem_id, mem_name from sy_acr_mem where acr_id = '5937020e4add150Y' order by mem_seq;");
            if (dt_pwdHint == null || dt_pwdHint.Rows.Count == 0) return;
            dd_pwd_hint.DataSource = dt_pwdHint;
            dd_pwd_hint.DataTextField = "mem_name";
            dd_pwd_hint.DataValueField = "mem_id";
            dd_pwd_hint.DataBind();

            DataTable dt_country = HDD.GetDataTable("select code, name from sy_country_list where is_active = 1 order by name;");
            if (dt_country == null || dt_country.Rows.Count == 0) return;
            DataRow dr_country = dt_country.NewRow();
            dr_country["name"] = "-- Select a country --";
            dr_country["code"] = "";
            dt_country.Rows.InsertAt(dr_country, 0);
            dd_country.DataSource = dt_country;
            dd_country.DataTextField = "name";
            dd_country.DataValueField = "code";
            dd_country.DataBind();
            dd_country.Items.FindByValue("US").Selected = true;

            DataTable dt_state = HDD.GetDataTable("select mem_name, mem_value1 from sy_acr_mem where acr_id = '2165f0cfce6e2e2L' order by mem_seq;");
            if (dt_state == null || dt_state.Rows.Count == 0) return;
            dd_state.DataSource = dt_state;
            dd_state.DataTextField = "mem_name";
            dd_state.DataValueField = "mem_value1";
            dd_state.DataBind();
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("MB_Registration: loadCombolists : Error : " + ex.Message);
        }
        finally
        {
            HDD = null;
        }
    }

    protected void btn_back_Click(object sender, EventArgs e)
    {
        try
        {
            if (Request.UrlReferrer != null && Request.UrlReferrer.ToString() != "")
                if (Request.Url.AbsoluteUri.Substring(0, Request.Url.AbsoluteUri.LastIndexOf('/')) != Request.UrlReferrer.ToString().Substring(0, Request.UrlReferrer.ToString().LastIndexOf('/')))
                    Response.Redirect(Request.UrlReferrer.ToString());
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : MB_Registration : btn_back_Click() : " + ex.Message);
        }
    }

    protected void btn_register_Click(object sender, EventArgs e)
    {
        string sResult = string.Empty;
        if (InputValidate())
        {
            string sMaxBloxSupportEmail = string.Empty;
            if (ConfigurationManager.AppSettings["registration_notification_email"] != null && ConfigurationManager.AppSettings["registration_notification_email"].Trim() != "")
                sMaxBloxSupportEmail = ConfigurationManager.AppSettings["registration_notification_email"];
            else
                sMaxBloxSupportEmail = "maxblox_support@cellarstone.com";
            
            if (SubmitData())
                sResult = "Your request has been successfully processed. An email has been sent to your mail id, including the instructions to activate your MaxBlox account. Please check your email to proceed with the activation request." +
                "<br><br>Feel free to contact " + sMaxBloxSupportEmail + " for any queries.";
            else
                sResult = "Your transaction has been successfully processed. However, we are unable to activate your account for you now. " +
                    "<br>Our system will automatically activate your account later. Please try to login after few hours. <br>Feel free to contact " + sMaxBloxSupportEmail + " for any queries.</font>";
            div_Reg.Visible = false;
            lbl_result.Text = wrapItAsMessage("&nbsp;<img src='Images/tick4.gif' border='0'>&nbsp;" + sResult, false);
            div_result.Visible = true;
            lbl_message.Text = "";
        }
    }

    private bool InputValidate()
    {
        security hdds = new security();
        HDDatabase HDD = null;
        string err = string.Empty;
        try
        {
            if (Session["servercon"] != null && Session["servercon"].ToString() != "")
                HDD = new HDDatabase(Session["servercon"].ToString());
            else
                HDD = new HDDatabase();
            if (!new CommonFunctions().ValidateEmailID(txt_user_id.Text))
            {
                lbl_message.Text = wrapItAsMessage("&nbsp;<img src='Images/error.gif' border='0'>&nbsp;Invalid User id.", true);
                return false;
            }
            if (HDD.GetTableRow("select * from ngcompanyuser where user_id in ('" + txt_user_id.Text.Replace("'", "''") + "');") != null)
            {
                lbl_message.Text = wrapItAsMessage("&nbsp;<img src='Images/error.gif' border='0'>&nbsp;User id already exists. Please provide another user id.", true);
                return false;
            }
            if (txt_new_pwd.Text != txt_confirm_pwd.Text)
            {
                lbl_message.Text = wrapItAsMessage("&nbsp;<img src='Images/error.gif' border='0'>&nbsp;Passwords does not match.", true);
                return false;
            }
            if (!hdds.validatePasswordLength(txt_new_pwd.Text, ref err))
            {
                lbl_message.Text = wrapItAsMessage("&nbsp;<img src='Images/error.gif' border='0'>&nbsp;" + err, true);
                return false;
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("MB_Registration: InputValidate: Error: " + ex.Message);
        }
        finally
        {
            hdds = null;
            HDD = null;
        }
        return true;
    }

    private Hashtable GetServerDetails()
    {
        HDDatabase HDD = null;
        Hashtable serverinfo = new Hashtable();
        try
        {
            if (Session["servercon"] != null && Session["servercon"].ToString() != "")
                HDD = new HDDatabase(Session["servercon"].ToString());
            else
                HDD = new HDDatabase(); 
            
            DataTable dt = HDD.GetDataTable("Select * from sy_pg_ctr where page_id = 'a74e0a342ddc69aN'");
            foreach (DataRow row in dt.Rows)
            {
                switch (row["control_id"].ToString().ToLower())
                {
                    case "company_version":
                        serverinfo.Add(row["control_id"].ToString().ToLower(), row["default_value"].ToString());
                        break;
                    case "dbname":
                        serverinfo.Add(row["control_id"].ToString().ToLower(), row["default_value"].ToString());
                        break;
                    case "dbuser":
                        serverinfo.Add(row["control_id"].ToString().ToLower(), row["default_value"].ToString());
                        break;
                    case "dbpassword":
                        serverinfo.Add(row["control_id"].ToString().ToLower(), row["default_value"].ToString());
                        break;
                    case "server":
                        serverinfo.Add(row["control_id"].ToString().ToLower(), row["default_value"].ToString());
                        break;

                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("MB_Registration: GetServerDetails: Error: " + ex.Message);
        }
        finally
        {
            HDD = null;
        }
        return serverinfo;
    }

    private string RandomString(int size, bool lowerCase)
    {
        StringBuilder builder = new StringBuilder();
        Random random = new Random();
        char ch;
        for (int i = 0; i < size; i++)
        {
            ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
            builder.Append(ch);
        }
        if (lowerCase)
            return builder.ToString().ToLower();
        return builder.ToString();
    }
    private string GetActivationKey()
    {
        StringBuilder builder = new StringBuilder();
        builder.Append(RandomString(8, false));
        return builder.ToString();
    }

    private bool SubmitData()
    {
        bool blnStatus = false;
        bool mailStatus = false;
        string strSql = string.Empty, content = string.Empty, af_row_id = string.Empty, act_code = string.Empty, company_id = string.Empty;
        ScreenReader SR = new ScreenReader();
        HDDatabase HDD = null;
        MBFunctions MBF = new MBFunctions();
        try
        {
            if (Session["servercon"] != null && Session["servercon"].ToString() != "")
                HDD = new HDDatabase(Session["servercon"].ToString());
            else
                HDD = new HDDatabase();
            
            act_code = GetActivationKey();
            af_row_id = SR.getHashKey();
            company_id = SR.getHashKey();

            //ngcompany
            strSql = "insert into ngcompany (company_id,af_row_id,activation_key,company_name,Address1,city,state,country,pincode,email,phone,created_date,modified_date,isactive) values " +
                         "('" + company_id.Replace("'", "''") + "','" + af_row_id + "','" + act_code + "','" + txt_company_name.Text.Replace("'", "''") +
                         "','" + txt_address.Text.Replace("'", "''") + "','" + txt_city.Text.Replace("'", "''") + "','" + dd_state.SelectedValue + "','" + dd_country.SelectedValue + "','" +
                         txt_postal_code.Text.Replace("'", "''") + "','" + txt_user_id.Text.Replace("'", "''") + "','" + txt_phone.Text.Replace("'", "''") + "','" +
                         System.DateTime.Now.ToUniversalTime() + "','" + System.DateTime.Now.ToUniversalTime() + "',0);";

            //ngcompanyserver
            Hashtable serverinfo = GetServerDetails();
            strSql += "insert into ngcompanyserver (af_row_id,company_id,server,dbname,dbuser,dbpassword,backup_frequency,company_version) values ('" + SR.getHashKey() + "','" + af_row_id + "','" + serverinfo["server"].ToString() + "','" + (serverinfo["dbname"].ToString() == "" ? company_id.Replace("'", "''") : serverinfo["dbname"].ToString()) + "','" + serverinfo["dbuser"].ToString() + "','" + serverinfo["dbpassword"].ToString() + "','<a href=''Default.aspx''>Click here to login to the company</a>','" + serverinfo["company_version"].ToString() + "');";

            //ngcompanyuser
            strSql += "insert into ngcompanyuser (af_row_id,company_id,user_id,password,hint_question,hint_answer,first_name,last_name) values ('650a333596bbf348','" + company_id.Replace("'", "''") + "','" + txt_user_id.Text.Replace("'", "''") + "','" + security.encrypt(txt_new_pwd.Text).Replace("'", "''") + "','" + dd_pwd_hint.SelectedValue.Replace("'", "''") + "','" + txt_hint_ans.Text.Replace("'", "''") + "','" + txt_first_name.Text.Replace("'", "''") + "','" + txt_last_name.Text.Replace("'", "''") + "');";

            SqlCommand sc_registration = new SqlCommand();
            sc_registration.CommandText = strSql;

            if (HDD.ExecuteCmdObj(sc_registration) > 1)
            {
                DataTable dt_emailresources = HDD.GetDataTable("select * from [sy_email_resources];");
                if (dt_emailresources != null && dt_emailresources.Rows.Count > 0)
                {
                    string sMaxBloxSupportEmail = string.Empty;
                    if (ConfigurationManager.AppSettings["registration_notification_email"] != null && ConfigurationManager.AppSettings["registration_notification_email"].Trim() != "")
                        sMaxBloxSupportEmail = ConfigurationManager.AppSettings["registration_notification_email"];
                    else
                        sMaxBloxSupportEmail = "maxblox_support@cellarstone.com";

                    DataRow[] dr_Welcome2MB = dt_emailresources.Select("[af_row_id] = 'cc35a72e56ee3676'");
                    if (dr_Welcome2MB.Length > 0)
                    {
                        content = dr_Welcome2MB[0]["content"].ToString();
                        content = content.Replace("$User$", txt_first_name.Text);
                        mailStatus = MBF.SentInEmailQueue(txt_user_id.Text.Replace("'", "''"), sMaxBloxSupportEmail, dr_Welcome2MB[0]["subject"].ToString(), content.Replace("'", "''"), 0, true);
                    } 
                    
                    DataRow[] dr_ActivateMB = dt_emailresources.Select("[af_row_id] = '5fe08411f2939940'");
                    if (dr_ActivateMB.Length > 0)
                    {
                        content = dr_ActivateMB[0]["content"].ToString();
                        content = content.Replace("$User$", txt_first_name.Text);
                        content = content.Replace("$Mail$", txt_user_id.Text);
                        content = content.Replace("$Key$", act_code);
                        content = content.Replace("$Path$", HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.LastIndexOf("/") + 1) + "mb_activation.aspx");
                        mailStatus = MBF.SentInEmailQueue(txt_user_id.Text.Replace("'", "''"), sMaxBloxSupportEmail, dr_ActivateMB[0]["subject"].ToString(), content.Replace("'", "''"), 0, true);
                    }

                    DataRow[] dr_RegMB = dt_emailresources.Select("[af_row_id] = 'c8f3c94acc01c6d9'");
                    if (dr_RegMB.Length > 0)
                    {
                        content = dr_RegMB[0]["content"].ToString();
                        content = content.Replace("$user_id$", txt_user_id.Text);
                        content = content.Replace("$first_name$", txt_first_name.Text);
                        content = content.Replace("$last_name$", txt_last_name.Text);
                        content = content.Replace("$company_name$", txt_company_name.Text);
                        content = content.Replace("$address$", txt_address.Text);
                        content = content.Replace("$phone$", txt_phone.Text);
                        content = content.Replace("$city$", txt_city.Text);
                        content = content.Replace("$pincode$", txt_postal_code.Text);
                        content = content.Replace("$country$", dd_country.SelectedIndex == dd_country.Items.Count - 1 ? dd_country.SelectedValue : dd_country.SelectedValue);
                        content = content.Replace("$state$", dd_state.SelectedValue);
                        mailStatus = MBF.SentInEmailQueue(sMaxBloxSupportEmail, sMaxBloxSupportEmail, dr_RegMB[0]["subject"].ToString(), content.Replace("'", "''"), 0, true);
                    }
                    blnStatus = true;
                }
            }
            else
                blnStatus = false;
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("MB_Registration: SubmitData: Error: " + e.Message);
            blnStatus = false;
        }
        finally
        {
            SR = null; HDD = null; MBF = null;
        }
        return blnStatus;
    }
    
}